<script setup>
import { ref, onMounted, inject } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useUserStore } from "../stores/user";
import { useRouter } from "vue-router";
import dayjs from "dayjs";

const articles = ref([]);
const total = ref(0);
const loading = ref(false);
const error = ref(null);
const router = useRouter();

const axios = inject("axios");

const userStore = useUserStore();

const userInfo = ref(null);
const page = ref(1);
const pageSize = ref(5);

const fetchArticles = async () => {
  try {
    console.log("UserStore");
    const res = await axios.get(`user/${userInfo.value?.userId}/articles`, {
      params: {
        page: page.value,
        pageSize: pageSize.value,
      },
    });
    console.log(res.data);
    if (res.data.code === 200) {
      articles.value = res.data.data.record;
      total.value = res.data.data.total;
      ElMessage.success("加载文章成功");
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (err) {
    error.value = "加载文章失败，请稍后再试。";
    ElMessage.error(err);
  } finally {
    loading.value = false;
  }
};

// 查看详情
const viewDetail = (id) => {
  // 跳转到详情页或打开模态框
  router.push(`/article/${id}`);
  // alert(`跳转至文章 ID: ${id} 的详情`);
};

// 删除文章前确认
const confirmDelete = (id) => {
  ElMessageBox.confirm("确定要删除该文章吗？此操作不可恢复", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await axios.delete(`/user/article/${id}`); // 替换为你的真实删除接口
        if (res.data.code === 200) {
          fetchArticles();
          ElMessage.success("删除成功");
        } else {
          ElMessage.error("删除失败");
        }
      } catch (err) {
        ElMessage.error("删除失败");
        console.error(err);
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

onMounted(() => {
  userInfo.value = userStore.userInfo.record;
  loading.value = true;
  fetchArticles();
});
</script>

<template>
  <div class="article-list">
    <div v-if="loading">暂无文章</div>
    <div v-else>
      <h2>我的文章</h2>

      <el-card
        v-for="article in articles"
        :key="article.id"
        class="article-card"
        shadow="hover"
      >
        <div class="card-content">
          <div class="info">
            <h3>{{ article.title }}</h3>
            <p>{{ article.describe || "暂无描述" }}</p>
            <small>发布时间：{{ dayjs(article.createdAt).format("YYYY年MM月DD日 HH:mm") }}</small>
          </div>
          <div class="actions">
            <el-button
              @click="viewDetail(article.articleId)"
              type="primary"
              plain
              >查看详情</el-button
            >
            <el-button
              @click="confirmDelete(article.articleId)"
              type="danger"
              plain
              >删除</el-button
            >
          </div>
        </div>
      </el-card>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading">加载中...</div>
      <div v-if="error" class="error">{{ error }}</div>
    </div>
  </div>
</template>

<style scoped>
.article-list {
  max-width: 800px;
  margin: 20px auto;
}

.article-card {
  margin-bottom: 16px;
}

.card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info {
  flex: 1;
}

.actions {
  display: flex;
  gap: 10px;
}

.loading,
.error {
  text-align: center;
  padding: 20px;
}
</style>
